<?php

namespace App\Service\CallingCards;

use App\Models\FeishuCallingCard\FeishuCallingCard;
use App\Service\Common\OssService;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use Kuafu\File\FileUtil;

class StoryImageService
{
    const FILE_NAME_PREFIX = 'kuafu_tiger_calling_cards_story_';

    // 背景图
    const BG1 = '0c/24/2d626cf584d7c72618dea96c01cb6473c8ee2eccb52e24e2f6c25fe36a43.png';
    // 苹方粗体
    const FONT1 = '96/ec/2276d8e77453e0e44f1e9633ee513396f2eeabb3d330f9e9306343b25fd9.ttf';
    // 苹方细体
    const FONT2 = '26/14/ce6927f34c31fe321110e7d7df6d252a9cee2235ce261aa8ab21c3e20908.ttf';

    protected static ?string $userShareLocalFile = null;
    protected static ?string $userAvatarLocalFile = null;

    public static function make(string $invitorId, int $urlId, string $storyTitle): array
    {
        $avatar = '';
        $name = '';
        if ('u' === mb_substr($invitorId, 0, 1)) {
            $body = RmsUserService::getRmsUserInfoByUserIds([(int)mb_substr($invitorId, 1)]);
            $avatar = $body['data'][0]['avatar'] ?? (FileUtil::domain() . '/dc/1a/ed20828b5fd6b855662c46f02278f54ec8552953f0a7c37df1ee94777d9f.png');
            $avatar = ltrim(parse_url($avatar, PHP_URL_PATH), '/');
            $name   = $body['data'][0]['username'] ?? '夸父炸串合伙人';
        } else {
            $card = FeishuCallingCard::find($invitorId);
            if (null === $card) {
                $card = FeishuCallingCard::find(1);
            }
            $avatar = $card->avatar;
            $name   = $card->name;
        }


        static::prepareResource($invitorId, $urlId, $avatar);
        $tmpFile = static::makeImage($name, $storyTitle);
        $arr = OssService::uploadFile($tmpFile, 'jpg');
        @unlink(static::$userShareLocalFile);
        @unlink(static::$userAvatarLocalFile);
        @unlink($tmpFile);
        return $arr;
    }

    /**
     * 生成图片
     * @param string $invitorId
     * @param string $storyTitle
     * @param string $name
     * @return string
     */
    protected static function makeImage(string $name, string $storyTitle)
    {
        $lines = [];
        $line = '';
        for ($i = 0; $i < mb_strlen($storyTitle); $i++) {
            $line .= mb_substr($storyTitle, $i, 1);
            if (mb_strlen($line) < 12) {
                continue;
            } else {
                $lines[] = $line;
                $line = '';
            }
        }
        if (strlen($line)) {
            $lines[] = $line;
        }
        $tmpFile = sys_get_temp_dir() . '/' . Str::random(10) . '.jpg';
        $image = Image::canvas(750, 980)
            ->insert(static::$userAvatarLocalFile, 'top-left', 87, 206)
            ->insert(static::tempFileName('bg1'))
            ->text($name . ' 推荐您阅读', 162, 245, function ($font) {
                $font->file(static::tempFileName('font2'));
                $font->size(24);
                $font->color('#979797');
            });
        $y = 428;
        foreach ($lines as $line) {
            $image->text($line, 88, $y, function ($font) {
                $font->file(static::tempFileName('font1'));
                $font->size(48);
                $font->color('#000000');
            });
            $y += 72;
        }
        $image->insert(static::$userShareLocalFile, 'top-left', 138, 683)
            ->save($tmpFile);
        return $tmpFile;
    }

    /**
     * 固定的文件在本地的临时地址
     * @param $name
     * @return string
     */
    protected static function tempFileName($name): string
    {
        return sys_get_temp_dir() . '/' . static::FILE_NAME_PREFIX . $name;
    }

    /**
     * 准备好资源图片
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected static function prepareResource(string $invitorId, $urlId, $avatar)
    {
        if (!self::checkSha256('bg1', static::BG1)) {
            self::downloadFile(static::BG1, static::tempFileName('bg1'));
        }
        if (!self::checkSha256('font1', static::FONT1)) {
            self::downloadFile(static::FONT1, static::tempFileName('font1'));
        }
        if (!self::checkSha256('font2', static::FONT2)) {
            self::downloadFile(static::FONT2, static::tempFileName('font2'));
        }

        static::$userShareLocalFile = sys_get_temp_dir() . '/' . Str::random(10);
        file_put_contents(static::$userShareLocalFile, WechatService::genStoryQrcode($invitorId, $urlId));
        Image::make(static::$userShareLocalFile)->resize(172, 172)->save(static::$userShareLocalFile);

        static::$userAvatarLocalFile = sys_get_temp_dir() . '/' . Str::random(10);
        self::downloadFile($avatar, static::$userAvatarLocalFile);
        Image::make(static::$userAvatarLocalFile)->resize(62, 62)->save(static::$userAvatarLocalFile);
    }

    /**
     * 下载oss文件到本地
     * @param string $url
     * @param string $localPath
     * @return void
     */
    protected static function downloadFile(string $url, string $localPath)
    {
        @unlink($localPath);
        file_put_contents($localPath, file_get_contents(FileUtil::domain() . '/' . $url));
    }

    /**
     * 检查文件指纹
     * @param $name
     * @param $url
     * @return bool
     */
    protected static function checkSha256($name, $url): bool
    {
        $tempFilename = static::tempFileName($name);
        if (!is_readable($tempFilename)) {
            return false;
        }
        $sha256 = substr(str_replace('/', '', $url), 0, 64);
        if ($sha256 != hash_file('sha256', $tempFilename)) {
            return false;
        }
        return true;
    }
}
